import re

from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.images import SKUImageSerializer, SKUInfoSerializer
from apps.meiduo_admin.utils import PageNum


# skus/images/?page=1&pagesize=10
class SKUImagesView(ModelViewSet):
    permission_classes = [IsAdminUser]

    serializer_class = SKUImageSerializer

    queryset = SKUImage.objects.all()

    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        """重写create方法  不只是存入数据库  也要存入fdfs存储图片"""
        sku_id = request.data.get('sku')
        image = request.data.get('image')
        image_data = image.read()

        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return Response(status=status.HTTP_400_BAD_REQUEST)

        from fdfs_client.client import Fdfs_client
        # 获取fdfs对象
        client = Fdfs_client('utils/fastdfs/client.conf')

        # 上传图片到fastDFS
        res = client.upload_by_buffer(image_data)
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径  注意替换一下反斜杠
        image_url = res['Remote file_id'].replace('\\', '/')
        # 保存图片
        sku = SKU.objects.get(id=sku_id)
        sku.default_image = image_url
        sku.save()
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)

        return Response(
            {
                'sku_id': img.sku.id,
                'image_url': img.image.url,
            },
            status.HTTP_201_CREATED
        )

    def update(self, request, *args, **kwargs):
        sku_id = request.data.get('sku')
        image = request.data.get('image')
        image_data = image.read()

        sku_image_id = kwargs.get('pk')

        if not sku_image_id:
            return Response(status.HTTP_400_BAD_REQUEST)
        try:
            img = SKUImage.objects.get(id=sku_image_id)
            sku = SKU.objects.get(id=img.sku_id)
        except Exception as e:
            print(e)
            return Response(status.HTTP_400_BAD_REQUEST)

        now_del_image_url = img.image.url
        del_url = re.search(r'(group.*)', now_del_image_url).group(1)

        client = Fdfs_client('utils/fastdfs/client.conf')

        res = client.upload_by_buffer(image_data)
        if res['Status'] != 'Upload successed.':
            return Response(status.HTTP_403_FORBIDDEN)

        image_url = res['Remote file_id'].replace('\\', '/')
        sku.default_image = image_url
        sku.save()
        img.image = image_url
        img.save()

        client.delete_file(del_url)
        return Response(
            {
                'id': img.id,
                'sku_id': sku_id,
                'image_url': img.image.url,
            },
            status.HTTP_201_CREATED
        )

    def destroy(self, request, *args, **kwargs):
        pk = kwargs.get('pk')

        try:
            sku_img = SKUImage.objects.get(id=pk)
        except Exception as e:
            print(e)
            return Response(status.HTTP_400_BAD_REQUEST)

        now_del_image_url = sku_img.image.url
        del_url = re.search(r'(group.*)', now_del_image_url).group(1)
        client = Fdfs_client('utils/fastdfs/client.conf')
        client.delete_file(del_url)
        sku_img.delete()

        return Response(status.HTTP_204_NO_CONTENT)


# http://127.0.0.1:8000/meiduo_admin/skus/simple/
class SKUInfoView(ListAPIView):
    permission_classes = [IsAdminUser]
    queryset = SKU.objects.all()
    serializer_class = SKUInfoSerializer
